package ldh.im.fxbase.service;

import ldh.im.ImConfig;
import ldh.im.dto.business.item.DepartmentInfoItem;
import ldh.im.fxbase.dao.ImDepartmentDao;
import ldh.im.fxbase.data.pojo.ImDepartment;
import ldh.im.fxbase.data.pojo.status.ImDepartmentStatus;
import ldh.im.fxbase.util.BeanFactory;
import ldh.im.fxbase.util.RpcUtil;
import ldh.rpc.cache.CacheService;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ImDepartmentService {

    private ImDepartmentDao imDepartmentDao = BeanFactory.getInstance().getBean(ImDepartmentDao.class);

    public void saveOrUpdates(List<DepartmentInfoItem> departmentInfoItems) throws SQLException {
        if (departmentInfoItems.size() < 1) return;
        List<ImDepartment> imDepartmentList = departmentInfoItems.stream().map(this::toDepartment).collect(Collectors.toList());
        List<String> codeList = imDepartmentList.stream().map(d->d.getCode()).collect(Collectors.toList());
        List<ImDepartment> dbImDepartments = imDepartmentDao.getDepartmentByCodes(codeList);
        Set<String> dbCodes = dbImDepartments.stream().map(d->d.getCode()).collect(Collectors.toSet());

        List<ImDepartment> insertImDepartments = new ArrayList<>();
        List<ImDepartment> updateImDepartmentList = new ArrayList<>();

        for (ImDepartment department : imDepartmentList) {
            if (dbCodes.contains(department.getCode())) {
                updateImDepartmentList.add(department);
            } else {
                insertImDepartments.add(department);
            }
        }
        imDepartmentDao.batchInserts(insertImDepartments);
        imDepartmentDao.batchUpdates(updateImDepartmentList);
    }

    private ImDepartment toDepartment(DepartmentInfoItem departmentInfoItem) {
        ImDepartment imDepartment = new ImDepartment();
        CacheService cacheService = RpcUtil.getRpcBootstrap().getRpcConfig().getCacheService();
        String userId = (String) cacheService.getCache(ImConfig.LOGIN_USER_ID);
        imDepartment.setCurrentUserId(userId);
        imDepartment.setCode(departmentInfoItem.getOrgCode());
        imDepartment.setName(departmentInfoItem.getDepartmentName());
        imDepartment.setDescription(departmentInfoItem.getDesc());
        imDepartment.setStatus(ImDepartmentStatus.valueOf(departmentInfoItem.getStatus().name()));
        imDepartment.setParentCode(departmentInfoItem.getParentCode());
        imDepartment.setManagerUserId(departmentInfoItem.getManagerUserId());
        imDepartment.setOtherManagerUserIdSet(departmentInfoItem.getOtherManagerUserIdList());
        imDepartment.setCreateDateTime(new Date());
        imDepartment.setUpdateDateTime(new Date());
        return imDepartment;
    }
}
